# -*- coding: utf-8 -*-
from django.views.generic.simple import direct_to_template
from lr.bookcase.models import Bookcase
from lr.work.models import Visit, Work
from django.http import HttpResponseRedirect
from lr.cabinet.models import UserRels


def bookcase(request):
    """ Обработчик запроса книжного шкафа """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')
    
    if 'select' in request.GET:
        select = request.GET['select']
        if select == 'recommend':
            return bookcase_recommend(request)
        elif select == 'favorite':
            return bookcase_favorite(request)
    return bookcase_common(request)


def bookcase_recommend(request):
    """ Рекомендовано друзьями """
    friends = UserRels.objects.get(user=request.user).friends.all()
    lot = []
    for friend in friends:
        recommended = Bookcase.objects.get(user=friend).recommended.all()
        for work in recommended:
            lot.append(work)
    bookcase_data = {}
    bookcase_data['shelves'] = [{ 'title': u'Друзья рекомендуют', 'works': lot }]
    bookcase_data['right_offset'] = 200
    return direct_to_template(request, 'bookcase/bookcase.html', bookcase_data)

 
def bookcase_favorite(request):
    """ Избранное друзей """
    friends = UserRels.objects.get(user=request.user).friends.all()
    lot = []
    for friend in friends:
        favorites = Bookcase.objects.get(user=friend).favorites.all()
        for work in favorites:
            lot.append(work)
    bookcase_data = {}
    bookcase_data['shelves'] = [{ 'title': u'Избранное друзей', 'works': lot }]
    bookcase_data['right_offset'] = 200
    return direct_to_template(request, 'bookcase/bookcase.html', bookcase_data)
    


def bookcase_common(request):
    """ Список своего избранного, рекомендованного и прочитанного """
    bookcase = Bookcase.objects.get(user=request.user)
    shelves = []
    lot = bookcase.favorites.all()
    if len(lot) > 0:
        shelves.append({ 'title': u'Избранное', 'works': lot })
    lot = bookcase.recommended.all()
    if len(lot) > 0:
        shelves.append({ 'title': u'Вы рекомендуете', 'works': lot })
    
    temp = Visit.objects.filter(visitor__user=request.user).only('visitor__work'). \
    values('visitor__work').order_by('visitor__work').distinct()
    lot = []
    for w in temp:
        lot.append(Work.objects.get(id=w['visitor__work']))
    
    if len(lot) > 0:
        shelves.append({ 'title': u'Вы читали', 'works': lot })
    
    if len(shelves) == 0:
        shelves.append({ 'title': u'Вы читали', 'works': [] })
    
    bookcase_data = {}
    bookcase_data['shelves'] = shelves
    bookcase_data['right_offset'] = 200
    return direct_to_template(request, 'bookcase/bookcase.html', bookcase_data)
